<template>
  <view>
    <nav-bar :page-title="lang.pageTitle"/>
    <view :class="['padding-30 text-color text-28', locale]" style="padding-bottom: 260rpx;">
      <!-- header -->
      <view class="center margin-bottom-60">
        <text class="text-40">{{ lang.title }}</text>
      </view>

      <!-- selected file section -->
      <view v-if="!selectedFile" class="center gap-40 upload-box" @click="selectPDF">
        <image src="/static/upload/upload.svg" class="upload-icon"/>
        <view class="upload-text">{{ toolBoxLang.selectFile }}</view>
      </view>

      <view v-else class="card flex-between selected-file">
        <view class="flex-center gap-20" style="width: 70%;">
          <view :class="['padding-30 radio-20 center type pdf']">
            <image src="/static/ext/pdf.svg" class="file-icon"/>
          </view>
          <view class="text-to text-32">{{ selectedFile.name }}</view>
        </view>
        <view class="column-center gap-20">
          <button class="btn preview" @click="previewFile(selectedFile)">{{ toolBoxLang.preview }}</button>
          <button class="btn delete" @click="removeFile">{{ toolBoxLang.delete }}</button>
        </view>
      </view>

      <!-- بەت تاللاش قىسمى -->
      <view class="card margin-top page-section" v-if="selectedFile">
        <view class="text-32 margin-bottom-20">{{ toolBoxLang.selectPages }}</view>

        <view class="input-group">
          <view class="input-label">{{ lang.pageInputLabel }}</view>
          <input
              v-model="pageInput" :class="['text-32 text-align-center zh-CN page-input']" pattern="[0-9,-]*"
              placeholder="1,2,3,1-5" @blur="handlePageInput" @input="validateInput"
          />
        </view>

        <!-- تاللانغان بەتلەر تىزىملىكى -->
        <view v-if="formattedRanges.length >= 1" class="selected-ranges">
          <view v-for="(range, index) in formattedRanges" :key="index" class="flex-between range-item">
            <view class="text-32">{{ range }} {{ otherLang.page }}</view>
            <image src="/static/globalIcon/close.svg" class="icon-40" @click="removeRange(index)"/>
          </view>
        </view>
      </view>

      <!-- result -->
      <view v-if="result" class="result-card">
        <view class="center result-header">
          <text class="text-32 color-white">{{ toolBoxLang.splitComplete }}</text>
        </view>

        <view class="result-content">
          <view class="flex-between result-item">
            <view class="text-32 color-dark-grey">{{ toolBoxLang.pageCount }}</view>
            <view class="result-item-value text-color">{{ result.page_count }} {{ otherLang.page }}</view>
          </view>

          <view class="flex-between result-item">
            <view class="text-32 color-dark-grey">{{ toolBoxLang.fileName }}</view>
            <view style="width: 70%">
              <view class="text-32 text-to">{{ getFileName(result.url) }}</view>
            </view>
          </view>

          <!-- 临时写法， 后期修改-->
          <view class="flex-between gap-20" style="justify-content: space-around">
            <!--            <view class="color-white radio-30 center file share" @click="shareFile">{{ toolBoxLang.share }}</view>-->
            <view class="color-white radio-30 center file preview" @click="previewFile(result)">
              {{ toolBoxLang.preview }}
            </view>
            <view class="color-white radio-30 center file download" @click="handleDownload">
              {{ toolBoxLang.download }}
            </view>
            <view class="color-white radio-30 center file print" @click="printFile">{{ toolBoxLang.print }}</view>
          </view>
        </view>
      </view>
      <!-- start button -->
      <view class="padding-30 footer">
        <button class="center start-btn" :disabled="!(selectedFile && pageRanges.length >= 1)" @click="handleAction">
          {{ isConverted ? toolBoxLang.selectNewFile : toolBoxLang.startSplit }}
        </button>
      </view>
    </view>
  </view>
</template>

<script lang="ts">
import {splitPdfUrl} from "@/services/office";
import NavBar from "@/components/nav-bar/nav-bar.vue";
import tips from "@/utils/tips";
import NumberKeyboard from "@/components/NumberKeyboard/NumberKeyboard.vue";
import {getFileName} from "@/utils/utils";

interface FileObject {
  url?: string;
  path?: string;
  name?: string;
}

export default {
  components: {NumberKeyboard, NavBar},
  data() {
    return {
      value: '',
      selectedFile: null,
      pageInput: '',
      pageRanges: [],
      result: null,
      loading: false,

      isConverted: false
    }
  },

  computed: {
    toolBoxLang() {
      return this.$t('toolBox')
    },
    lang() {
      return this.$t('toolBox.splitPdf')
    },
    formattedRanges() {
      return this.pageRanges.map(range => {
        if (Array.isArray(range)) {
          return `${range[0]}-${range[1]}`;
        }
        return `${range}`;
      });
    }
  },
  methods: {
    getFileName,
    // select pdf
    selectPDF() {
      uni.chooseMessageFile({
        count: 1,
        type: 'file',
        extension: ['pdf'],
        success: (res) => {
          const {path, name} = res.tempFiles[0]
          console.log({path, name})
          this.selectedFile = {path, name}
        },
      })
    },

    // preview file
    previewFile(file: FileObject) {
      if (file.url) {
        uni.downloadFile({
          url: file.url,
          success: (res) => {
            if (res.statusCode === 200) {
              uni.openDocument({
                filePath: res.tempFilePath,
                fileType: 'pdf',
                success: () => {
                  console.log(this.toolBoxLang.openSuccess);
                },
              });
            }
          },
        });
      } else {
        uni.openDocument({
          filePath: file.path,
          fileType: 'pdf',
          success: () => {
            console.log(this.lang.openSuccess);
          },
          fail: () => {
            tips.toast(this.lang.openFailed);
          }
        });
      }
    },

    // remove selected file
    removeFile() {
      this.selectedFile = null
      this.pageRanges = []
      this.result = null
    },
    // validate input
    validateInput(e: any) {
      const value = e.target.value;
      if (!/^[0-9,-]*$/.test(value)) {
        this.pageInput = value.replace(/[^0-9,-]/g, '');
      }
    },
    // remove selected range
    handlePageInput() {
      if (!this.pageInput) {
        tips.toast(this.lang.selectPage)
        return
      }

      const ranges = this.pageInput.split(',').map(part => part.trim());
      const processedRanges = [];

      ranges.forEach(range => {
        if (range.includes('-')) {
          // دائىرىلىك بەتلەر (1-5)
          const [start, end] = range.split('-').map(num => parseInt(num));
          if (start && end && start <= end) {
            processedRanges.push([start, end]);
          }
        } else {
          // page number (1)
          const pageNum = parseInt(range);
          if (pageNum) {
            processedRanges.push(pageNum);
          }
        }
      });

      if (processedRanges.length) {
        this.pageRanges = [...this.pageRanges, ...processedRanges];
        this.pageInput = '';
      }
    },

    // remove range
    removeRange(index: number) {
      this.pageRanges.splice(index, 1)
    },

    // submit
    handleSubmit() {
      uni.showLoading()
      // validate page ranges
      console.log("handleSubmit =-=-=-", this.pageRanges)
      const formattedRanges = this.pageRanges.map(range => {
        return Array.isArray(range) ? range : [range, range];
      });

      console.log("formattedRanges -=-==", formattedRanges);

      uni.uploadFile({
        url: splitPdfUrl,
        filePath: this.selectedFile.path,
        name: 'file',
        formData: {
          page_ranges: JSON.stringify(formattedRanges)
        },
        success: (res) => {
          const {data} = JSON.parse(res.data)
          this.isConverted = true
          this.result = data
          tips.toast(this.toolBoxLang.splitSuccess)
        },
        fail: (err) => {
          tips.toast(this.toolBoxLang.splitFailed)
        },
        complete: () => {
          uni.hideLoading()
        }
      });
    },

    handleAction() {
      if (this.isConverted) {
        this.removeFile()
        this.isConverted = false
      } else {
        this.handleSubmit()
      }
    },

    // download
    handleDownload() {
      let {url} = this.result;
      if (!url) {
        tips.toast(this.toolBoxLang.emptyUrl)
        return;
      }

      uni.downloadFile({
        url,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.openDocument({
              filePath: res.tempFilePath,
              fileType: 'pdf',
              showMenu: true,
              success: () => {
                console.log(this.toolBoxLang.openSuccess);
              },
              fail: () => {
                tips.toast(this.toolBoxLang.openFailed);
              }
            });
          }
        }
      });
    },

    // print file
    printFile() {
      const {result: {url, page_count}, selectedFile: {name}} = this;
      if (!url) {
        tips.toast(this.toolBoxLang.emptyUrl)
        return;
      }
      uni.navigateTo({
        url: `/pages/file/print_file?pages=${page_count}&file=${encodeURIComponent(JSON.stringify({url, name}))}`
      })
    },

    // share file
    shareFile() {
      let {url} = this.result;
      if (!url) {
        tips.toast(this.lang.emptyUrl)
        return;
      }

      uni.downloadFile({
        url,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.shareFileMessage({
              filePath: res.tempFilePath,
              fileName: getFileName(url),
              success: () => {
                console.log('ھۆججەت يوللاندى');
              }
            });
          }
        }
      });
    },
  }
}
</script>

<style scoped lang="scss">
.upload-box {
  border: 2px dashed $uni-border-color;
  padding: 60rpx;

  &:active {
    background: $uni-bg-color-hover;
  }

  .upload-icon {
    width: 80rpx;
    height: 80rpx;
  }

  .upload-text {
    font-size: 32rpx;
    color: #666;
  }
}

.selected-file {
  .file-icon {
    width: 60rpx;
    height: 60rpx;
  }

  .btn {
    font-size: 24rpx;
    color: #fff;
    width: 128rpx;
    border-radius: 12rpx;
    padding: 0;
    margin: 0;

    &.preview {
      background: #007AFF;
    }

    &.delete {
      background: #ff3b30;
    }
  }
}

/* style for the page input section */
.page-section {
  .input-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .input-label {
    color: #666;
  }

  .page-input {
    height: 90rpx;
    background: #f5f5f5;
    border: 1px solid #e0e0e0;
    border-radius: 16rpx;
    padding: 0 30rpx;
  }

  .page-input:focus {
    border-color: #007AFF;
    background: #fff;
  }

  .selected-ranges {
    padding-top: 16rpx;

    .range-item {
      padding: 20rpx 30rpx;
      background: #f1f1f1;
      border-radius: 16rpx;
      margin-top: 16rpx;
    }
  }
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);

  .start-btn {
    width: 100%;
    height: 90rpx;
    background: linear-gradient(to right, #34c759, #30d158);
    color: #fff;
    font-size: 32rpx;
    border-radius: 46rpx;

    &.start-btn[disabled] {
      background: linear-gradient(to right, #ccc, #ddd);
    }
  }
}


.result-card {
  margin-top: 30rpx;
  border-radius: 20rpx;
  background: #ffffff;
  overflow: hidden;

  .result-header {
    background: $uni-color-success;
    padding: 20rpx;
  }

  .result-content {
    padding: 30rpx;

    .result-item {
      margin-bottom: 20rpx;

      .result-item-value {
        font-size: 28rpx;
        font-weight: 500;
      }
    }

    .file {
      width: 140rpx;
      line-height: 34rpx;
      padding: 14rpx 20rpx;
      transition: opacity 0.3s;

      &:active {
        opacity: 0.8;
      }

      &.share {
        background: $uni-color-info;
      }

      &.preview {
        background: $uni-color-warning;
      }

      &.download {
        background: $uni-color-success;
      }

      &.print {
        background: $uni-color-primary;
      }
    }
  }
}
</style>